'''
实现将图片批量导出到word，文字在左图片在右
'''
import os
from PIL import Image, ImageOps
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
from docx.oxml import OxmlElement

def add_page_number(doc):
    """为每个页面添加页码"""
    sections = doc.sections
    for section in sections:
        footer = section.footer
        paragraph = footer.paragraphs[0] if footer.paragraphs else footer.add_paragraph()
        paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

        run = paragraph.add_run()

        # 插入“第”字
        run.add_text("第 ")

        # 插入当前页码域代码
        fld_char1 = OxmlElement('w:fldChar')
        fld_char1.set(qn('w:fldCharType'), 'begin')
        instr_text = OxmlElement('w:instrText')
        instr_text.set(qn('xml:space'), 'preserve')
        instr_text.text = 'PAGE \\* MERGEFORMAT'
        fld_char2 = OxmlElement('w:fldChar')
        fld_char2.set(qn('w:fldCharType'), 'end')

        run._r.append(fld_char1)
        run._r.append(instr_text)
        run._r.append(fld_char2)

        # 插入“页，共”字
        run.add_text(" 页，共 ")

        # 插入总页数域代码
        fld_char3 = OxmlElement('w:fldChar')
        fld_char3.set(qn('w:fldCharType'), 'begin')
        instr_text2 = OxmlElement('w:instrText')
        instr_text2.set(qn('xml:space'), 'preserve')
        instr_text2.text = 'NUMPAGES \\* MERGEFORMAT'
        fld_char4 = OxmlElement('w:fldChar')
        fld_char4.set(qn('w:fldCharType'), 'end')

        run._r.append(fld_char3)
        run._r.append(instr_text2)
        run._r.append(fld_char4)

        # 插入“页”
        run.add_text(" 页")

def __create_temp_dir__(dir):
    if os.path.exists(dir) is False:
        os.mkdir(dir)

def images_to_word(image_folder, output_word):
    # 获取文件夹中的所有图片文件
    image_files = [f for f in os.listdir(image_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tif', '.tiff'))]

    # 创建一个新的Word文档
    doc = Document()

    # 设置页面宽度和高度
    section = doc.sections[0]
    section.page_width = Inches(8.5)
    section.page_height = Inches(11)
    section.left_margin = Inches(0.5)
    section.right_margin = Inches(0.5)
    section.top_margin = Inches(0.5)
    section.bottom_margin = Inches(0.5)

    # 定义左右半边的宽度
    left_width = Inches(3.0)  # 左半边宽度（英寸）
    right_width = Inches(5.0)  # 右半边宽度（英寸）

    image_count = len(image_files)
    for idx, filename in enumerate(image_files, start=1):
        print('图片'+filename+'正在导入word中')
        image_path = os.path.join(image_folder, filename)
        # 打开图片并修正方向
        __create_temp_dir__(temp_folder)
        with Image.open(image_path) as image:
            # 检测并修正图片方向
            image = ImageOps.exif_transpose(image)
            # 保存修正后的图片到一个临时文件
            image_path = os.path.join(temp_folder, filename)
            image.save(image_path)
        img = Image.open(image_path)

        # 计算图片缩放比例，保持图片比例
        img_width, img_height = img.size
        aspect_ratio = img_width / img_height
        max_width = 5.0  # 右半边宽度（英寸），减去边距
        max_height = 10  # Word页面高度（英寸），减去边距

        if aspect_ratio > max_width / max_height:
            img_width = max_width
            img_height = max_width / aspect_ratio
        else:
            img_height = max_height
            img_width = max_height * aspect_ratio

        # 创建一个表格，包含两列
        table = doc.add_table(rows=1, cols=2)
        table.style = 'Table Grid'
        table.cell(0, 0).width = left_width
        table.cell(0, 1).width = right_width

        # 移除表格边框
        tbl = table._tbl
        for cell in tbl.iter_tcs():
            tcPr = cell.get_or_add_tcPr()

            # 移除边框
            tcBorders = OxmlElement('w:tcBorders')
            top = OxmlElement('w:top')
            top.set(qn('w:val'), 'none')
            left = OxmlElement('w:left')
            left.set(qn('w:val'), 'none')
            bottom = OxmlElement('w:bottom')
            bottom.set(qn('w:val'), 'none')
            right = OxmlElement('w:right')
            right.set(qn('w:val'), 'none')
            tcBorders.append(top)
            tcBorders.append(left)
            tcBorders.append(bottom)
            tcBorders.append(right)
            tcPr.append(tcBorders)

            # 移除底纹
            shading_elm = OxmlElement('w:shd')
            shading_elm.set(qn('w:val'), 'clear')
            shading_elm.set(qn('w:color'), 'auto')
            shading_elm.set(qn('w:fill'), 'FFFFFF')  # 白色填充
            tcPr.append(shading_elm)

        # 添加文字说明
        fileAttr = filename.split('.')[0].split('-')
        if len(fileAttr) != 4:
            print('图片' + filename + '文件名不符合规范无法解析，自动跳过导入')
            continue
        paragraph = table.cell(0, 0).paragraphs[0]
        run = paragraph.add_run('Material: ' + fileAttr[1])
        run.bold = True
        run.font.size = Pt(16)
        paragraph.add_run('\n')
        paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT

        paragraph = table.cell(0, 0).add_paragraph()
        run = paragraph.add_run('Finish: ' + fileAttr[2])
        run.bold = True
        run.font.size = Pt(16)
        paragraph.add_run('\n')
        paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT

        paragraph = table.cell(0, 0).add_paragraph()
        run = paragraph.add_run('Oricin: ' + fileAttr[3])
        run.bold = True
        run.font.size = Pt(16)
        paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT

        # 添加图片
        paragraph = table.cell(0, 1).paragraphs[0]
        run = paragraph.add_run()
        run.add_picture(image_path, width=Inches(img_width), height=Inches(img_height))
        paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

        # 只在非最后一张图片后添加分页符
        if idx < image_count:
            doc.add_page_break()

    # 添加页码
    add_page_number(doc)

    # 保存Word文档
    doc.save(output_word)

# 使用示例
# image_folder = 'D:\\001-Signorino'
image_folder = 'D:\\0001-SNB'
temp_folder = image_folder + '_temp'
# output_word = 'D:\\001-Signorino.docx'
output_word = 'D:\\0001-SNB.docx'
images_to_word(image_folder, output_word)
